import { getWechatCode, wechatLogin, loginWithCode } from '@/utils/wechat.js'

export const useLoginStore = defineStore('login', () => {
  let token = $ref('')
  let openId = $ref('')

  const updateToken = (payload) => {
    token = payload
  }
  const isLogin = computed(() => {
    if (isNilOrEmpty(token)) return false
    const decoded = weappJwtDecode(token)
    return dayjs().isBefore(dayjs.unix(decoded.exp))
  })

  const tokenUserId = computed(() => {
    if (isNilOrEmpty(token)) return null
    const decoded = weappJwtDecode(token)
    return decoded.userId
  })

  const router = useRouter()

  const { clearUser, updateUserInfo, getSysMenu } = useUserStore()
  const { clearBase } = useBaseStore()

  const aLogin = async (url, formData) => {
    clearUser()
    const { data, status } = await Fetch(url, { method: 'post', data: formData })
    if (status !== 200 || data.code !== 0) {
      return data.msg
    }
    token = data.result
    await updateUserInfo()
    await getSysMenu()
    return 'ok'
  }

  const aLoginByScan = async (code) => {
    const { data, status } = await Fetch(`/api/auth/scanlogin/${code}`)
    if (status !== 200 || data.code !== 0) {
      return data.msg
    }
    clearUser()
    token = data.result
    if (router) {
      router.replace('/index')
    }
  }

  const aLogout = async () => {
    clearUser()
    clearBase()
    if (router) {
      await router.replace('/index')
    } else {
      location.replace('/index')
    }
    token = ''
  }


  // 微信小程序登录
  const aWechatLogin = async () => {
    try {
      // 获取微信登录code
      const code = await getWechatCode()
      console.log('获取到微信登录code:', code)

      // 使用code进行后端登录
      const loginResult = await loginWithCode(code)
      console.log(loginResult,'loginResult____________________________');

      // 更新token
      token = loginResult.token || loginResult
      openId = loginResult.openid || loginResult
      // 更新用户信息
      await updateUserInfo()
      await getSysMenu()

      return 'ok'
    } catch (error) {
      console.error('微信登录失败:', error)
      return error.message || '微信登录失败'
    }
  }

  // 完整的微信登录流程（包含用户信息获取）
  const aWechatLoginWithUserInfo = async (off=false) => {
    try {
      const loginData = await wechatLogin(off)

      if (loginData.isNewLogin) {
        // 使用code进行后端登录
        const loginResult = await loginWithCode(loginData.code)

        // 更新token
        token = loginResult.access_token || loginResult
        openId = loginResult.openid || loginResult

        // 更新用户信息
        const result =  await updateUserInfo()

        return {
          success: result,
          userInfo: loginData.userInfo
        }
      } else {
        return {
          success: true,
          message: '登录状态有效'
        }
      }
    } catch (error) {
      console.error('微信登录流程失败:', error)
      return {
        success: false,
        error: error.message || '微信登录失败'
      }
    }
  }

  return {
    token: $$(token),
    openId: $$(openId),
    isLogin,
    tokenUserId,
    aLogin,
    aLogout,
    aLoginByScan,
    updateToken,
    aWechatLogin,           // 新增：仅获取code登录
    aWechatLoginWithUserInfo, // 新增：完整登录流程
  }
}, { unistorage: { key: 'config-login' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useLoginStore, import.meta.hot))
